/*
 * GrantRequestStatusChangeCancelledView.java
 *
 * Created on November 20, 2008, 10:11 AM
 */

package researchgrants.parts.GrantRequest.statusChanges;

import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import researchgrants.parts.GrantRequest.GrantRequest;
import researchgrants.parts.GrantRequest.perennialStipends.PanelsPerennialStipends;
import researchgrants.parts.GrantRequest.perennialStipends.PerennialStipends;
import researchgrants.parts.LoggedData.LoggedData;
import researchgrants.parts.LoggedData.panels.LoggedDataPanelsDate;
import researchgrants.parts.LoggedData.panels.LoggedDataPanelsText;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import researchgrants.parts.db.Db;
import researchgrants.parts.panelsManager.CompoundDataPanelsManager;
import researchgrants.parts.panelsManager.LoggedDataPanelsManager;

/**
 * A view to edit an existing or input a new GrantRequestStatusChangeAwarded
 * @author  DOStudent1
 */
public class GrantRequestStatusChangeAwardedView extends GrantRequestStatusChangeView {

    private Window parent;
    private final static int hgap=0;

    // defferentiate between new (to be saved) and existing StatusChangeAwarded
    private boolean isNew;

    // if existing StatusChangeAwarded, this is it
    private GrantRequestStatusChangeAwarded grantRequestStatusChangeAwarded;

    // if new StatusChangeAwarded, need this supplement data (to connect to upon save)
    private GrantRequest grantRequest;
    
    // global-style components
    JButton btnSaveAll, btnCancel;
    LoggedDataPanelsManager decisionDateView, nonMonetaryAwardView;
    CompoundDataPanelsManager perennialStipendsView;
    private ActionListener savedActionListener;
    private ActionListener cancelActionListener;
    
    /** Will creates a new (empty) Award and connect it to the given grantRequest*/
    public GrantRequestStatusChangeAwardedView(Window parent, GrantRequest grantRequest, ActionListener savedActionListener, ActionListener cancelActionListener) {
//        super()
        initComponents();
        this.parent=parent;
        this.grantRequest=grantRequest;
        this.savedActionListener=savedActionListener;
        this.cancelActionListener=cancelActionListener;
        isNew=true;

        initDisplay();
    }

    /** displays an existing Award */
    public GrantRequestStatusChangeAwardedView(Window parent, GrantRequestStatusChangeAwarded grantRequestStatusChangeAwarded) {
        initComponents();
        this.parent=parent;
        this.grantRequestStatusChangeAwarded=grantRequestStatusChangeAwarded;
        isNew=false;

        initDisplay();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        pnlID = new javax.swing.JPanel();
        lblCaptionId = new javax.swing.JLabel();
        lblId = new javax.swing.JLabel();
        pnlDecisionDate = new javax.swing.JPanel();
        lblCaptionDecisionDate = new javax.swing.JLabel();
        pnlFieldDecisionDate = new javax.swing.JPanel();
        pnlPerennialStipends = new javax.swing.JPanel();
        pnlPerennialStipends2 = new javax.swing.JPanel();
        lblCaptionPerennialStipends = new javax.swing.JLabel();
        pnlFieldPerennialStipends = new javax.swing.JPanel();
        pnlNonMonetaryAward = new javax.swing.JPanel();
        lblCaptionNonMonetaryAward = new javax.swing.JLabel();
        pnlFieldNonMonetaryAward = new javax.swing.JPanel();
        pnlOptionalButtons = new javax.swing.JPanel();

        setName("Form"); // NOI18N
        setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS));

        pnlID.setName("pnlID"); // NOI18N
        pnlID.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(researchgrants.ResearchGrantsApp.class).getContext().getResourceMap(GrantRequestStatusChangeAwardedView.class);
        lblCaptionId.setText(resourceMap.getString("lblCaptionId.text")); // NOI18N
        lblCaptionId.setName("lblCaptionId"); // NOI18N
        pnlID.add(lblCaptionId);

        lblId.setText(resourceMap.getString("lblId.text")); // NOI18N
        lblId.setName("lblId"); // NOI18N
        pnlID.add(lblId);

        add(pnlID);

        pnlDecisionDate.setName("pnlDecisionDate"); // NOI18N
        pnlDecisionDate.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionDecisionDate.setText(resourceMap.getString("lblCaptionDecisionDate.text")); // NOI18N
        lblCaptionDecisionDate.setName("lblCaptionDecisionDate"); // NOI18N
        pnlDecisionDate.add(lblCaptionDecisionDate);

        pnlFieldDecisionDate.setName("pnlFieldDecisionDate"); // NOI18N
        pnlFieldDecisionDate.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        pnlDecisionDate.add(pnlFieldDecisionDate);

        add(pnlDecisionDate);

        pnlPerennialStipends.setName("pnlPerennialStipends"); // NOI18N
        pnlPerennialStipends.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        pnlPerennialStipends2.setName("pnlPerennialStipends2"); // NOI18N
        pnlPerennialStipends2.setLayout(new java.awt.GridBagLayout());

        lblCaptionPerennialStipends.setText(resourceMap.getString("lblCaptionPerennialStipends.text")); // NOI18N
        lblCaptionPerennialStipends.setName("lblCaptionPerennialStipends"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        pnlPerennialStipends2.add(lblCaptionPerennialStipends, gridBagConstraints);

        pnlFieldPerennialStipends.setName("pnlFieldPerennialStipends"); // NOI18N
        pnlFieldPerennialStipends.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        pnlPerennialStipends2.add(pnlFieldPerennialStipends, gridBagConstraints);

        pnlPerennialStipends.add(pnlPerennialStipends2);

        add(pnlPerennialStipends);

        pnlNonMonetaryAward.setName("pnlNonMonetaryAward"); // NOI18N
        pnlNonMonetaryAward.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, hgap, 0));

        lblCaptionNonMonetaryAward.setText(resourceMap.getString("lblCaptionNonMonetaryAward.text")); // NOI18N
        lblCaptionNonMonetaryAward.setName("lblCaptionNonMonetaryAward"); // NOI18N
        pnlNonMonetaryAward.add(lblCaptionNonMonetaryAward);

        pnlFieldNonMonetaryAward.setName("pnlFieldNonMonetaryAward"); // NOI18N
        pnlFieldNonMonetaryAward.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        pnlNonMonetaryAward.add(pnlFieldNonMonetaryAward);

        add(pnlNonMonetaryAward);

        pnlOptionalButtons.setName("pnlOptionalButtons"); // NOI18N
        pnlOptionalButtons.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
        add(pnlOptionalButtons);
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel lblCaptionDecisionDate;
    private javax.swing.JLabel lblCaptionId;
    private javax.swing.JLabel lblCaptionNonMonetaryAward;
    private javax.swing.JLabel lblCaptionPerennialStipends;
    private javax.swing.JLabel lblId;
    private javax.swing.JPanel pnlDecisionDate;
    private javax.swing.JPanel pnlFieldDecisionDate;
    private javax.swing.JPanel pnlFieldNonMonetaryAward;
    private javax.swing.JPanel pnlFieldPerennialStipends;
    private javax.swing.JPanel pnlID;
    private javax.swing.JPanel pnlNonMonetaryAward;
    private javax.swing.JPanel pnlOptionalButtons;
    private javax.swing.JPanel pnlPerennialStipends;
    private javax.swing.JPanel pnlPerennialStipends2;
    // End of variables declaration//GEN-END:variables

 
    // displays the content
    private void initDisplay() {
        // must init the button so it will be enabled or disabled by the other fields
        if (isNew) {
            // only if new, add the buttons
            btnSaveAll=new JButton("Save Award");
            btnSaveAll.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    createNewAwardFromFields();
                }
            });

            btnCancel=new JButton("Leave Unchanged");
            btnCancel.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    cancelActionListener.actionPerformed(e);
                }
            });
            
        }

        
        ///////////////////////////
        // Displays the content
        ///////////////////////////
    
        if (isNew) {
            lblId.setText("<Auto>");
        } else {
            lblId.setText(Integer.toString(grantRequestStatusChangeAwarded.getStatusChangeId()));
        }

        
        LoggedData decisionDate=null, nonMonetaryAward=null;
        PerennialStipends perennialStipends=null;
        if (!isNew) {
            decisionDate=grantRequestStatusChangeAwarded.getLoggedDataDecisionDate();
            nonMonetaryAward=grantRequestStatusChangeAwarded.getLoggedDataNonMonetaryAward();
            perennialStipends=grantRequestStatusChangeAwarded.getPerennialStipends();
        }

        decisionDateView=createLoggedDataPanelManager(false, isNew, new LoggedDataPanelsDate(), parent, decisionDate, pnlFieldDecisionDate);
        nonMonetaryAwardView=createLoggedDataPanelManager(false, isNew, new LoggedDataPanelsText(), parent, nonMonetaryAward, pnlFieldNonMonetaryAward);

        {
            perennialStipendsView=new CompoundDataPanelsManager();
            perennialStipendsView.setMandatory(false);
            perennialStipendsView.startAsNew(isNew);
            {
                PanelsPerennialStipends panelsPerennialStipends=new PanelsPerennialStipends();
                if (!isNew) {
                    panelsPerennialStipends.setData(perennialStipends);
                } else {
                    panelsPerennialStipends.setDefaultData(grantRequest.getExpectedPerennialStipends());
                }
                ChangeListener changeEventListener = new PerennialStipendsValidator(panelsPerennialStipends);
                panelsPerennialStipends.addChangeListener(changeEventListener);
                panelsPerennialStipends.setParent(parent, pnlFieldPerennialStipends);
                perennialStipendsView.setPanels(panelsPerennialStipends);
            }
            pnlFieldPerennialStipends.removeAll();
            pnlFieldPerennialStipends.add(perennialStipendsView);
            perennialStipendsView.display();
        }
        
        

        pnlOptionalButtons.removeAll();
        if (isNew) {
            pnlOptionalButtons.setLayout(new GridLayout());
            pnlOptionalButtons.add(btnSaveAll);
            pnlOptionalButtons.add(btnCancel);
        }
        
    }

    // Creates a new GrantRequestStatusChangeAward from the fields
    private void createNewAwardFromFields() {
        try {
            // creates the common GrantRequestStatusChange part
            int newStatusChangeId = GrantRequestStatusChangeAwarded.createNewStatusChangeForGrantRequest(grantRequest, GrantRequestStatusChangeAwarded.dbString);

            // saves the independent data
            Connection conn = Db.openDbConnection();
            PreparedStatement statement = Db.createPreparedStatement(conn, "INSERT INTO tblGrantRequestsStatusChangesAwarded (GrantRquestStatusChangeID, DecisionDateRef, NonMonetaryAwardRef, PerennialStipendsId) VALUES (?, ?, ?, ?)");

            statement.setInt(1, newStatusChangeId);
            
            statement.setInt(2, saveLoggedDataPanelsManagerData(decisionDateView));
            statement.setInt(3, saveLoggedDataPanelsManagerData(nonMonetaryAwardView));

            ((PanelsPerennialStipends)perennialStipendsView.getPanels()).saveData();
            statement.setInt(4, ((PanelsPerennialStipends)perennialStipendsView.getPanels()).getPerennialStipends().getId());


            
            statement.executeUpdate();
            statement.close();
            Db.closeDbConnection(conn);

            // loads the newly created Award
            this.grantRequestStatusChangeAwarded=GrantRequestStatusChangeAwarded.getByStatusChangeId(newStatusChangeId);
            // refreshes the GrantRequest to reload the manually added data
            grantRequest.refreshData();
            
            // notifies the listeners. the GrantRequestView needs to redisplay
            savedActionListener.actionPerformed(new ActionEvent(this, 1, "Saved new Award StatusChange"));

        } catch (SQLException ex) {
            Logger.getLogger(GrantRequestStatusChangeAwardedView.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
    }

    ////////////////////////////////
    // Validation check
    ////////////////////////////////
    
    // each individual component is validated/invalidated seperately, using its designated Listener
    // the entire form is revalidated after any individual change

    // local flags that change as the field's data becomes valid or invalid
    private boolean isParennialStipendsValid=true;

    // going to validate the entire form, using the validity of all individual items
    private void revalidateEntire() {
        if (isNew) {
            btnSaveAll.setEnabled((isParennialStipendsValid));
        }
    }
    
    // a check for validation of the perennialStipends
    private class PerennialStipendsValidator implements ChangeListener {

        PanelsPerennialStipends panelsPerennialStipends;
        
        private PerennialStipendsValidator(PanelsPerennialStipends panelsPerennialStipends) {
            this.panelsPerennialStipends=panelsPerennialStipends;
        }

        public void stateChanged(ChangeEvent e) {
            isParennialStipendsValid=panelsPerennialStipends.isValid();
            // revalidating the entire form
            revalidateEntire();
        }
    }

}
